package com.mall.common.dao.impl;

import static com.mall.common.bean.CommonAttributes.PATH_SEPARATOR;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;

import com.mall.common.dao.AreaDao;
import com.mall.common.domain.AreaDomain;

@Repository
public class AreaDaoImpl extends BaseDaoImpl<AreaDomain, Long> implements AreaDao {
	
	@SuppressWarnings("unchecked")
	public List<AreaDomain> getRootAreaList() {
		String hql = "from AreaDomain area where area.parent is null";
		return entityManager.createQuery(hql).getResultList();
	}
	
	@SuppressWarnings("unchecked")
	public List<AreaDomain> getParentAreaList(AreaDomain area) {
		String hql = "from AreaDomain area where area != ?1 and area.id in(:ids)";
		String[] ids = area.getPath().split(PATH_SEPARATOR);
		return entityManager.createQuery(hql).setParameter(1, area).setParameter("ids", ids).getResultList();
	}
	
	@SuppressWarnings("unchecked")
	public List<AreaDomain> getChildrenAreaList(AreaDomain area) {
		String hql = "from AreaDomain area where area != ?1 and area.path like ?2";
		return entityManager.createQuery(hql).setParameter(1, area).setParameter(2, area.getPath() + "%").getResultList();
	}

	public Boolean isNameUnique(Long parentId, String oldName, String newName) {
		if (StringUtils.equalsIgnoreCase(newName, oldName)) {
			return true;
		}
		if (parentId == null) {
			String hql = "from AreaDomain area where area.name = :name and area.parent is null";
			return entityManager.createQuery(hql).setParameter("name", newName).getResultList().size() == 0;
		} else {
			String hql = "from AreaDomain area where area.name = :name and area.parent.id = :parentId";
			return entityManager.createQuery(hql).setParameter("name", newName).setParameter("parentId", parentId).getResultList().size() == 0;
		}
	}

}
